#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <set>

using namespace std;

class QueryText {
public:
    void read(const char *filename) {
        ifstream ifs(filename);
        if (!ifs) {
            cerr << "file is not found" << endl;
            return;
        }

        string line;
        int lineNumber = 1;
        while (getline(ifs, line)) {
            _lines.push_back(line);

            istringstream iss(line);
            string word;
            while (iss >> word) {
                _wordLineNumbers[word].insert(lineNumber);
                ++_wordFrequency[word];
            }
            ++lineNumber;
        }
    }

    void query(const string &word) {
        auto it = _wordFrequency.find(word);
        if (it != _wordFrequency.end()) {
            cout << word << " occurs " << _wordFrequency[word] << " times." << endl;
            cout << "-----------------------------------------------------------" << endl;
            for (auto &lineNum : _wordLineNumbers[word]) {
                cout << "(line" << lineNum << ")" << _lines[lineNum - 1] << endl;
            }
            cout << "-----------------------------------------------------------" << endl;
        }
        else {
            cout << word << " is not found " << endl;
        }
    }
private:
    vector<string> _lines;
    map<string, set<int>> _wordLineNumbers;
    map<string, int> _wordFrequency;
};

void test() {
    string queryword("and");

    QueryText qt;
    qt.read("china_daily.txt");
    qt.query(queryword);
}

int main()
{
    test();
    return 0;
}
